# -*- coding: utf-8 -*-
# @Time : 2024/2/3 2:06 PM 
# @Author : Wayne
# @Email : 1
# @File : group_sum.py
# @Project : young_python_demo
# @DESCRIPTION :


"""
data是要分组求和的列表套字典数据，
data是要分组求和的列表套字典数据，
group_keys是一个元组，表示要根据哪些键进行分组,
sum_keys参数传递了一个元组，其中包含了要进行求和的键。
数据分组汇总函数
"""
def sum_by_group(data_list, group_fields, sum_fields):
    grouped_data = {}

    for data in data_list:
        key = tuple(data[field] for field in group_fields)
        if key not in grouped_data:
            grouped_data[key] = {field: float(data[field]) for field in sum_fields}
        else:
            for field in sum_fields:
                grouped_data[key][field] += float(data[field])
    data_sum = []
    for key in grouped_data:
        temp_dict = {group_fields[i]: key[i] for i in range(len(group_fields))}
        temp_dict.update({field: str(grouped_data[key][field]) for field in sum_fields})
        data_sum.append(temp_dict)
    return data_sum


data1 = [
    {
        "shop_code": "123",
        "total": "101",
        "ware_name": "ck01"
    },
    {
        "shop_code": "123",
        "total": "122",
        "ware_name": "ck01"
    },
    {
        "shop_code": "4323",
        "total": "32",
        "ware_name": "ck01"
    }
]

group_keys1 = ["ware_name", "shop_code"]
sum_keys1 = ["total"]
data_sum = sum_by_group(data1, group_keys1, sum_keys1)
print(data_sum)
